<template>
  <div class="print">
    <div class="top">
      <el-upload
        ref="uploadRef"
        drag
        action=""
        multiple
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-change="handleChange"
        :auto-upload="false"
        accept=".pdf"
        :show-file-list="false"
      >
        <div class="el-upload__text">拖入文件检测页数或者 <em class="c-p">导入文件</em></div>
        <div style="width: 100%; height: 200px; min-height: 200px" class="f-c" @click.stop="">
          <Table
            :isShowPagination="false"
            :data="state.fileList"
            row-key="id"
            :isFlex1="true"
            :isShowSelection="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column label="文件名称" prop="fileName"></el-table-column>
            <el-table-column label="文件类型" prop="fileType"></el-table-column>
            <el-table-column label="页数" prop="filePageNum">
              <template #header>
                <div class="f-r-s">
                  <span>页数</span>
                  <span>总：{{ totalPages }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80">
              <template #default="scope">
                <!-- 全局控制的编辑 -->
                <!-- 编辑 -->
                <el-button link @click="handleDelete(scope.$index, scope.row)" type="danger"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </Table>
        </div>
      </el-upload>
    </div>
    <div>
      <el-button class="start" @click="startDo" :disabled="customizationList.length == 0">
        开始定制</el-button
      >
      <el-button
        class="start"
        @click="resetDo"
        :disabled="state.fileList.length == state.defaultFileList.length"
      >
        重新定制</el-button
      >
      <el-button class="start" @click="resetUpload" :disabled="state.defaultFileList.length == 0">
        重新上传文件</el-button
      >
    </div>

    <div class="bottom">
      <div class="bottom-left">
        <Setting
          v-if="allDataInfo.length > 0"
          :settingList="allDataInfo"
          @submit="onSettingSubmit"
        />
      </div>
      <div class="bottom-right f-c" v-if="state.finalText">
        <div class="drawer-title-item">
          <p></p>
          <span>文本输出</span>
        </div>
        <div class="final">{{ state.finalText }}</div>
        <div>
          <el-button type="primary" @click="onCopy">复制</el-button>
          <el-button type="primary" @click="onResult">结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox, genFileId } from 'element-plus'
import { reactive, ref, onMounted } from 'vue'
import { createLoadingTask } from 'vue3-pdfjs/esm'
import Table from '@renderer/components/table/Table.vue'
import Setting from './Setting.vue'
import { useUserDB } from '@renderer/database/useUserDB'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const { addOrder, getCurrentUser } = useUserDB()

const uploadRef = ref(null)

const state = reactive({
  fileList: [],
  defaultFileList: [],
  finalText: ''
})
const totalPages = computed(() => {
  return state.fileList.reduce((acc, current) => {
    return acc + current.filePageNum
  }, 0)
})
function beforeUpload(file) {
  const isPDF = file.type === 'application/pdf'
  if (!isPDF) {
    console.error('请上传有效的 PDF 文件')
    return false
  }
  console.log(file)

  let isHas = state.defaultFileList.some((item) => item.fileName == file.name)
  if (isHas) {
    ElMessage.error('存在同名文件，请重新上传')
    return false
  }
  return true
}

async function getPdfPageCount(file) {
  try {
    const arrayBuffer = await readFileAsArrayBuffer(file)
    const num = getPdfPageCount1(arrayBuffer)
    return num
  } catch (error) {
    console.error('PDF 处理失败:', error)
    return 0
  }
}
async function getPdfPageCount1(fileArrayBuffer) {
  const loadingTask = createLoadingTask(fileArrayBuffer)
  const dev = await loadingTask.promise

  const numPages = dev.numPages
  return numPages
}
async function handleChange(file, fileList) {
  if (!beforeUpload(file.raw)) {
    console.error('文件不符合要求，无法处理')
    return
  }
  console.log(fileList)

  try {
    let processedFiles = await Promise.all(
      [...fileList].map(async (element, index) => ({
        fileName: element.name,
        fileType: 'PDF',
        filePageNum: await getPdfPageCount(element.raw),
        id: index + 1,
        file: element.raw
      }))
    )
    processedFiles = sortByFileName(processedFiles)

    state.fileList = processedFiles
    state.defaultFileList = JSON.parse(JSON.stringify(processedFiles))
  } catch (error) {
    console.error('文件处理失败:', error)
    ElMessage.error('文件处理失败')
  }
}
/**
 * 根据文件名对数组进行排序
 *
 * @param arr 需要排序的数组，数组元素应包含 fileName 属性
 * @returns 排序后的数组
 */
function sortByFileName(arr) {
  return [...arr].sort((a, b) => {
    // 使用 localeCompare 进行排序，支持中文拼音和数字排序
    return a.fileName.localeCompare(b.fileName, 'zh-CN', {
      numeric: true, // 按数值排序数字
      sensitivity: 'base' // 忽略大小写和音调差异
    })
  })
}
function readFileAsArrayBuffer(file) {
  return new Promise((resolve, reject) => {
    if (!(file instanceof File)) {
      reject(new Error('传入的不是有效的文件对象'))
      return
    }
    const reader = new FileReader()
    reader.onload = (event) => resolve(event.target.result)
    reader.onerror = () => reject(new Error('文件读取失败'))
    reader.readAsArrayBuffer(file)
  })
}

function handleExceed(files, fileList) {
  console.warn(`限制上传 1 个文件，已选择 ${files.length} 个文件`)
  uploadRef.value.clearFiles()
}

function handleDelete(index, row) {
  const newArray = state.defaultFileList.filter((item) => item.id !== row.id)
  state.defaultFileList = newArray

  const newArray1 = state.fileList.filter((item) => item.id !== row.id)
  state.fileList = newArray1
  // state.fileList.splice(index, 1)
  uploadRef.value.handleRemove(row.file)
}

const customizationList = ref([])
const handleSelectionChange = (val) => {
  console.log('val', val)
  customizationList.value = val
}
const allDataInfo = ref([])
// 开始定制
const startDo = () => {
  console.log('开始定制')
  if (customizationList.value && customizationList.value.length > 0) {
    allDataInfo.value.push({
      customizationList: customizationList.value,
      name: `定制${allDataInfo.value.length + 1}`
    })

    customizationList.value.forEach((item) => {
      state.fileList.splice(state.fileList.indexOf(item), 1)
      uploadRef.value.handleRemove(item.file)
    })
  }
}
// 重置定制
const resetDo = () => {
  allDataInfo.value = []
  state.fileList = JSON.parse(JSON.stringify(state.defaultFileList))
  state.finalText = ''
}
const orderInfo = ref({})
// 账单输出
const onSettingSubmit = (data) => {
  console.log('data', data)
  orderInfo.value = data
  let content = ''
  data.settingList.forEach((item) => {
    content += item.content
  })

  content = `${content}共计---${data.totalPrice}\n\n备注：${data.remarks || '--'}`
  console.log(content)

  state.finalText = content
}
/**
 * 异步函数，用于复制文本到剪贴板
 *
 * @returns 无返回值
 */
async function onCopy() {
  try {
    // 使用 navigator.clipboard.writeText 复制文本
    await navigator.clipboard.writeText(state.finalText)
    ElMessage.success('复制成功')
  } catch (error) {
    console.error('复制失败:', error)
  }
}

function onResult() {
  console.log('onResult')
  const timestampSeconds = Math.floor(Date.now() / 1000)
  const fileName = `定制账单-${timestampSeconds}`
  ElMessageBox.confirm('是否确定结算', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(async () => {
      let user = await getCurrentUser()
      let orderList = JSON.parse(JSON.stringify(user.orderList || []))
      let obj = {
        name: fileName,
        content: state.finalText,
        time: new Date().toLocaleString('zh-CN'),
        totalPrice: orderInfo.value.totalPrice
      }

      orderList = [...orderList, obj]
      addOrder(user.userName, orderList)


      resetUpload()

      router.push('/order')
      ElMessage.success('结算成功，已生成订单')
      console.log('结算成功，已生成订单', orderList)

    })
    .catch(() => {})
}

function resetUpload() {
  uploadRef.value.clearFiles()
  state.fileList = []
  state.defaultFileList = []
  customizationList.value = []
  state.finalText = ''
  allDataInfo.value = []
}
onMounted(() => {})
</script>

<style lang="scss" scoped>
.print {
  height: 100%;
  display: flex;
  flex-direction: column;

  .top {
    height: 260px;
    min-height: 260px;
  }
  .bottom {
    flex: 1;
    display: flex;
    gap: 24px;
    .bottom-left {
      width: 40%;
      height: 100%;
      // border-right: 1px solid #ebeef5;
    }
    .bottom-right {
      flex: 1;
      gap: 16px;
      .final {
        white-space: pre-wrap;
        padding: 8px;
        border: 1px solid #202020;
      }
    }
  }
}

.start {
  margin-bottom: 16px;
}
</style>
<style>
.el-upload {
  cursor: auto !important;
}
.el-upload-dragger {
  cursor: auto !important;
  background: #fff;
  border-width: 0;
  padding: 0;
  border-radius: 0;
}
.is-dragover {
  background: #fff !important;
  padding: 0 !important;
  border-width: 0 !important;
}
.el-upload__text {
  text-align: left !important;
  font-size: 16px !important;
  margin-bottom: 10px;
}
</style>
